package com.losl.framework.web.service;

import cn.hutool.core.util.IdUtil;
import com.losl.common.constant.Constant;
import com.losl.common.core.domain.entity.SysUser;
import com.losl.common.core.domain.model.LoginUser;
import com.losl.common.core.redis.RedisCache;
import com.losl.common.util.ServletUtils;
import com.losl.common.util.StringUtils;
import com.losl.system.mapper.SysUserMapper;
import com.losl.system.service.SysRoleService;
import com.losl.system.service.SysUserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.compress.utils.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Token验证处理
 *
 * @author Maxwell
 */
@Service
public class TokenService {
    /**
     * 令牌标识
     */
    @Value("${token.header}")
    private String header;

    /**
     * 令牌秘钥
     */
    @Value("${token.secret}")
    private String secret;

    /**
     * 令牌过期时间
     */
    @Value("${token.expireTime}")
    private Integer expireTime;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysUserMapper userMapper;

    private static final long MINUTE = 60;
    private static final long HOUR = 3600;
    private static final long DAY = 3600 * 24;

    /**
     * 获取用户身份信息
     *
     * @param request
     * @return
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            Claims claims = parseToken(token);
            String uuid = (String) claims.get(Constant.LOGIN_USER_KEY);
            String tokenKey = getTokenKey(uuid);
            return redisCache.getCacheObject(tokenKey);
        }
        return null;
    }

    /**
     * 从request中获取令牌
     *
     * @param request
     * @return
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        return token;
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret.getBytes())
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 得到用户在redis中的key
     *
     * @param uuid
     * @return
     */
    public String getTokenKey(String uuid) {
        return Constant.LOGIN_TOKEN_KEY + uuid;
    }

    /**
     * 创建令牌
     *
     * @return
     */
    public String createToken(LoginUser loginUser) {
        String uuid = IdUtil.simpleUUID();
        loginUser.setToken(uuid);
        SysUser sysUser = userMapper.selectUserByName(loginUser.getUsername());
        loginUser.setUser(sysUser);
        String roleKey = roleService.getById(sysUser.getRole()).getRoleKey();
        if ("*".equals(roleKey)) {
            loginUser.setPermissions(Sets.newHashSet("*"));
        } else {
            String[] keys = roleKey.split(",");
            loginUser.setPermissions(Sets.newHashSet(keys));
        }

        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constant.LOGIN_USER_KEY, uuid);
        return Jwts.builder().addClaims(claims).signWith(SignatureAlgorithm.HS256, secret.getBytes()).compact();
    }

    /**
     * 匿名用户创建令牌
     */
    public String tokenForAnonymous(LoginUser loginUser) {
        String uuid = IdUtil.simpleUUID();
        loginUser.setToken(uuid);
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * DAY);
        loginUser.setUser(null);
        loginUser.setPermissions(Sets.newHashSet("."));
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constant.LOGIN_USER_KEY, uuid);
        return Jwts.builder().addClaims(claims).signWith(SignatureAlgorithm.HS256, secret).compact();
    }

    /**
     * 刷新token
     *
     * @param loginUser
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * DAY);
        redisCache.setCacheObject(Constant.LOGIN_TOKEN_KEY + loginUser.getToken(), loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 检测用户是否过期
     */
    public boolean isExpire(LoginUser loginUser) {
        if (loginUser.getExpireTime() > System.currentTimeMillis()) {
            return true;
        }
        refreshToken(loginUser);
        return false;
    }

    /**
     * 从token中获取用户名
     */
    public String getUUID(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 验证令牌有效期
     */
    public void vertifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime < 20 * 60 * 1000) {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除登陆用户
     */
    public void deleteLoginUser(LoginUser user) {
        redisCache.deleteObject(user.getToken());
    }

    /**
     * 得到用户名
     */
    public String getUserName() {
        LoginUser loginUser = getLoginUser(ServletUtils.getRequest());
        if (StringUtils.isNull(loginUser)) {
            return "";
        }
        return loginUser.getUsername();
    }

}
